package dongze.com.ckdj.activity;

import android.content.DialogInterface;
import android.databinding.DataBindingUtil;
import android.databinding.Observable;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.widget.GridLayout;

import com.android.databinding.library.baseAdapters.BR;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import dongze.com.ckdj.R;
import dongze.com.ckdj.adapter.InformationSpinnerAdapter;
import dongze.com.ckdj.databinding.InformationItemSpinnerBinding;
import dongze.com.ckdj.databinding.InformationItemTextBinding;
import dongze.com.ckdj.databinding.model.InformationItemSpinnerModel;
import dongze.com.ckdj.databinding.model.InformationItemTextModel;
import dongze.com.ckdj.fragment.EmptyContentFragment;
import dongze.com.ckdj.fragment.NamePlateWorkLoadFragment;
import dongze.com.ckdj.map.MapUtil;
import io.reactivex.observers.DisposableObserver;

/**
 * Created by fanqwz on 2017/9/4.
 */

public class NamePlateWorkLoadActivity extends ProgressableActivity {
    @BindView(R.id.basic_info_container)
    GridLayout mBasicInfoLayout;
    InformationItemTextModel brandModel = new InformationItemTextModel();
    InformationItemSpinnerModel voyageModel = new InformationItemSpinnerModel();
    String brandcode;
    MapUtil mapUtil;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_name_plate_work_load);
        ButterKnife.bind(this);
        mapUtil = new MapUtil(getAppCompenent());

        brandModel.setKey("品牌");
        brandModel.setValue(getIntent().getStringExtra("brandname"));
        brandcode = getIntent().getStringExtra("brandcode");
        if (brandModel.getValue() == null || brandcode == null) {
            new AlertDialog.Builder(this)
                    .setMessage("没有品牌信息")
                    .setCancelable(false)
                    .setNegativeButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            finish();
                        }
                    })
                    .create()
                    .show();
        }
        addBasicInfoItem(brandModel);

        voyageModel.setKey("航次");
        voyageModel.addOnPropertyChangedCallback(onVoyageChange);
        addDropDownInfoItem(voyageModel);

        getSupportFragmentManager().beginTransaction()
                .add(R.id.fragment_container, new EmptyContentFragment())
                .commitAllowingStateLoss();

        loadVoyage();
    }

    @Override
    protected void onDestroy() {
        mapUtil.dispose();
        super.onDestroy();
    }

    private void addBasicInfoItem(InformationItemTextModel model) {
        InformationItemTextBinding binding = DataBindingUtil.inflate(LayoutInflater.from(this), R.layout.information_item_text, mBasicInfoLayout, false);
        binding.getRoot().setTag(binding);
        binding.setVehicleInformationItemText(model);
        int count = mBasicInfoLayout.getColumnCount();
        GridLayout.LayoutParams params = new GridLayout.LayoutParams(GridLayout.spec(mBasicInfoLayout.getChildCount() / count, 1), GridLayout.spec(mBasicInfoLayout.getChildCount() % count, 1));
        params.width = (getResources().getDisplayMetrics().widthPixels) / count;

//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//            params = new GridLayout.LayoutParams(GridLayout.spec(mBasicInfoLayout.getChildCount() / count, 1, 0.5f), GridLayout.spec(mBasicInfoLayout.getChildCount() % count, 1, 0.5f));
//        }

        int margin = getResources().getDimensionPixelSize(R.dimen.basic_info_item_margin);
        params.setMargins(margin, margin, margin, margin);
        mBasicInfoLayout.addView(binding.getRoot(), params);
    }

    private void addDropDownInfoItem(InformationItemSpinnerModel model) {
        InformationItemSpinnerBinding binding = DataBindingUtil.inflate(LayoutInflater.from(this), R.layout.information_item_spinner, mBasicInfoLayout, false);
        binding.getRoot().setTag(binding);
        binding.setVehicleInformationItemSpinner(model);
        int count = mBasicInfoLayout.getColumnCount();
        GridLayout.LayoutParams params = new GridLayout.LayoutParams(GridLayout.spec(mBasicInfoLayout.getChildCount() / count, 1), GridLayout.spec(mBasicInfoLayout.getChildCount() % count, 1));
        params.width = (getResources().getDisplayMetrics().widthPixels) / count;

//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//            params = new GridLayout.LayoutParams(GridLayout.spec(mBasicInfoLayout.getChildCount() / count, 1, 0.5f), GridLayout.spec(mBasicInfoLayout.getChildCount() % count, 1, 0.5f));
//        }

        int margin = getResources().getDimensionPixelSize(R.dimen.basic_info_item_margin);
        params.setMargins(margin, margin, margin, margin);
        mBasicInfoLayout.addView(binding.getRoot(), params);
    }

    private void loadVoyage() {
        mapUtil.getVoyage(brandcode, new DisposableObserver<List<String>>() {
            @Override
            protected void onStart() {
                super.onStart();
                doProcessing();
            }

            @Override
            public void onNext(List<String> value) {
                if (value.size() > 0) {
                    String[] arr = new String[value.size()];
                    value.toArray(arr);
                    voyageModel.setValues(arr);
                    voyageModel.setPosition(0);
                    onVoyageChange.onPropertyChanged(null, BR.position);
                }
            }

            @Override
            public void onError(Throwable e) {
                finishProcessing();
            }

            @Override
            public void onComplete() {
                finishProcessing();
            }
        });
    }

    Observable.OnPropertyChangedCallback onVoyageChange = new Observable.OnPropertyChangedCallback() {
        @Override
        public void onPropertyChanged(Observable sender, int propertyId) {
            if (propertyId == BR.position) {
                NamePlateWorkLoadFragment fragment = new NamePlateWorkLoadFragment();
                Bundle arg = new Bundle();
                arg.putString("brandcode", brandcode);
                if (voyageModel.getValues() != null)
                    arg.putString("voyage", voyageModel.getValues()[voyageModel.getPosition()]);
                fragment.setArguments(arg);
                getSupportFragmentManager().beginTransaction()
                        .replace(R.id.fragment_container, fragment)
                        .commitAllowingStateLoss();
            }
        }
    };
}
